package com.sc.byahi.open.client;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.sc.byahi.open.shared.LatestState;

public class OpenController implements ValueChangeHandler<String> {

	private Menu menu = new Menu();
	private Stage stage = new Stage();
	private HomeView homeView = new HomeView();

	private static OpenController controller = new OpenController();

	private OpenController() {
		History.addValueChangeHandler(this);
		
	}

	public static OpenController get() {
		return controller;
	}

	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();
		if ("home".equals(token)) {
			openDashboard();
		}
		// If you are adding an entry here, add it to stage.java also.
	}

	private void openDashboard() {
		final HasWidgets byahiContent = RootPanel.get("byahi-content");
		byahiContent.clear();

		HasWidgets menuContent = RootPanel.get("menu-container");
		menuContent.clear();
		menuContent.add(menu);

		HasWidgets stagingContent = RootPanel.get("stage-container");
		stagingContent.clear();
		stage.setText();
		stagingContent.add(stage);

		final HasWidgets logout = RootPanel.get("logout");
		logout.clear();
		OpenService.Util.getInstance().getLatestState(new AsyncCallback<LatestState>() {

			@Override
			public void onSuccess(LatestState state) {
				VerticalPanel v = new VerticalPanel();
				if(!"".equals(state.getNotice())){
					v.add(new Notice(state.getNotice())) ;
				}

				if ("".equals(state.getCurrentUser())) {
					logout.add(new HTML("<a href=\"" + state.getLoginURL() + "\"  id=\"signout-img\" alt=\"Sign out\"><img src=\"/images/exit.png\"></a>"));
				} else{
					logout.add(new HTML(state.getCurrentUser() + "<a href=\"" + state.getLogoutURL() + "\"  id=\"signout-img\" alt=\"Sign out\"><img src=\"/images/exit.png\"></a>"));
				}
				homeView.setLoggedIn(state);
				v.add(homeView) ;

//				byahiContent.add(homeView);
				byahiContent.add(v);
				
			}

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}
		});
	}
}
